<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formShow">
          <template #year>
            <el-date-picker v-model="form.value3" type="year" placeholder="年份" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <el-button @click="importHandleClick" :loading="importLoading">
          <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
        </el-button>
        <div class="ml-auto"></div>
        <FieldSelectBtn :fieldSelectConfig="fieldSelectConfig" @submit="query" />
      </template>
    </VTable>
    <!-- 导出中心 -->
    <!-- <DerivedCenter ref="DerivedCenterRef"></DerivedCenter> -->
  </VPage>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import { onMounted, ref, toRefs } from "vue"
import FieldSelectBtn from "@/views/salesInventory/components/FieldSelectBtn.vue"
import { inventoryBalanceList, inventoryBalanceExport } from "@/api/salesInventory"

// 导出中心
// import DerivedCenter from "@/components/DerivedCenter"
// const DerivedCenterRef = ref()
const importLoading = ref(false)
const importHandleClick = async (e) => {
  importLoading.value = true
  try {
    let condition = initForm(tableRef?.value?.getQueryForm())
    inventoryBalanceExport(condition).then((res) => {
      window.open(res?.data?.url, "noopener", "noreferrer")
      importLoading.value = false
    })
  } catch (error) {
    importLoading.value = false
  }
}
const tableRef = ref()
const formShow = ref(false)
// 查询
const query = () => {
  tableRef?.value.query()
}
import { getAloneEnum } from "@/utils/enumUtils"
// 获取下拉数据
onMounted(async () => {
  let oneKeys = ["amazonSite", "wmsAttribute", "warehouse"]
  let optData = await getAloneEnum(oneKeys)
  oneKeys.forEach((key) => {
    originOption.value[key] = optData?.[key]
  })
  originOption.value.amazonSite = originOption.value.amazonSite.map((v) => ({ ...v, value: v.label }))
  setTimeout(() => {
    formShow.value = true
  }, 100)
})

// 枚举 数据
const originOption = ref({})
const formOption = ref({ inline: true })
const publicStyle = { style: { width: "200px" } }
const fieldList = ref([
  {
    field: "warehouse_id",
    type: "select",
    originField: "warehouse",
    options: { placeholder: "仓库" },
    multiple: true,
    collapseTags: true,
    ...publicStyle,
  },
  {
    field: "warehouse_attr",
    type: "select",
    originField: "wmsAttribute",
    options: { placeholder: "仓库属性" },
    multiple: true,
    collapseTags: true,
    ...publicStyle,
  },
  {
    field: "country",
    type: "select",
    originField: "amazonSite",
    options: { placeholder: "国家" },
    multiple: true,
    collapseTags: true,
    ...publicStyle,
  },
  {
    field: "deadline_at",
    type: "dateTimeRangeNorm",
    itemProps: {
      type: "monthrange",
      format: "YYYY-MM",
      valueFormat: "YYYY-MM",
      shortcuts: [],
      clearable: false,
    },
    ...publicStyle,
  },
  {
    field: "dimension",
    type: "radio",
    options: {
      data: [
        { label: "周维度", value: "1" },
        { label: "月维度", value: "2" },
      ],
    },
    change: (e) => {
      tableRef?.value?.$table.loadColumn([])
      nextTick(() => {
        query()
      })
    },
    ...publicStyle,
  },
  {
    field: "skuRange",
    placeholder: "可批量搜索",
    type: "textarea",
    select: [{ label: "SKU", value: "sku" }],
    ...publicStyle,
  },
])
// 二级表头
const configColumns = [
  { title: "期初库存", key: "opening_inventory", width: 80 },
  { title: "期初金额", key: "opening_amount", width: 80 },
  { title: "入库数量", key: "in_inventory", width: 80 },
  { title: "入库金额", key: "in_amount", width: 80 },
  { title: "出库数量", key: "out_inventory", width: 80 },
  { title: "出库金额", key: "out_amount", width: 80 },
  { title: "期末数量", key: "closing_inventory", width: 80 },
  { title: "期末金额", key: "closing_amount", width: 80 },
]
// 初始化时间
import { parseTime } from "@/utils/ruoyi"
const initDate = () => {
  const temp = new Date()
  temp.setTime(temp.getTime() - 3600 * 1000 * 24 * 30)
  return [new Date(temp.setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 0))].map((d) => parseTime(d))
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      dimension: "1",
      deadline_at: initDate(),
      skuRange: { type: "sku", value: "" },
    },
  },
  // tooltipConfig: {
  //   showAll: true,
  // },
  border: "",
  // showOverflow: false,
  showHeaderOverflow: true,
  showFooterOverflow: true,
  columns: [
    { type: "seq", field: "seq", title: "序号", width: 60 },
    { field: "country", title: "国家", width: 100 },
    { field: "warehouse_name", title: "仓库", width: 100 },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        console.log("query")
        console.log(form)
        let params = {
          page: page.pageNum,
          page_size: page.pageSize,
          ...initForm(form),
        }

        return queryList(params)
      },
    },
  },
  showFooter: true,
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (["seq", "country"].includes(column.field)) return ""
        if (column.field === totalKey.value) {
          return "合计"
        } else {
          return sumNum(data, column.field)
        }
      }),
    ]
  },
})

// 合计
const sumNum = (list, field) => {
  let count = 0
  let fields = field?.split(".")
  let getObjKeys = (data) => {
    return fields.reduce((pre, cur) => pre[cur], data)
  }
  list.forEach((item) => {
    count += Number(getObjKeys(item, fields) || 0)
  })
  return count
}

// 表格字段模版筛选
import { filterColumns } from "@/views/salesInventory/components/method.js"

const totalKey = ref("")
const queryList = async (params) => {
  let res = await inventoryBalanceList(params)
  console.time("数据组装耗时")
  let date = []
  if (params.dimension == 1) {
    // 周维度
    res.data.forEach((item) => {
      item?.month_data.forEach((items, i) => {
        item.month_data[i] = items.week_data.map((v) => ({ ...v, month: `${items.month}-${v.week_num}` }))
      })
      item.month_data = item.month_data.flat()
      // 渠道数据 Arr 转 Obj
      item.month_data = Object.fromEntries(item.month_data.map((v) => [v.month, { ...v }]))
    })
    // 表头 日期
    date = Object.keys(res.data?.[0]?.month_data)
  } else {
    // 月维度
    res.data.forEach((item) => {
      item?.month_data?.forEach((items) => delete items.week_data)
      // 渠道数据 Arr 转 Obj
      item.month_data = Object.fromEntries(item.month_data.map((v) => [v.month, { ...v }]))
    })
    // 表头 日期
    date = Object.keys(res.data?.[0]?.month_data)
  }

  let columnsData = [...tableOptins.columns]
  // 按筛选条件添加  configColumns
  date.forEach((title) => {
    columnsData.push({
      title: title,
      align: "center",
      children: configColumns.map((v) => ({
        ...v,
        field: `month_data.${title}.${v.key}`,
        fieldShow: `month_data.month_data.${v.key}`,
      })),
    })
  })

  fieldSelectConfig.value.columns = [
    ...tableOptins.columns,
    {
      title: "时间维度",
      children: configColumns.map((v) => ({
        ...v,
        fieldShow: `month_data.month_data.${v.key}`,
      })),
    },
  ]
  const { columns, key } = filterColumns(columnsData, fieldSelectConfig.value.columnsShow)
  totalKey.value = key

  nextTick(() => {
    tableRef?.value?.$table.loadColumn(columns)
    tableRef?.value.updateScroll()
    console.timeEnd("数据组装耗时")
  })
  return res
}
const fieldSelectConfig = ref({
  save: "inventoryBalance",
  columnsShow: [],
  columns: [...tableOptins.columns, configColumns],
})

// 组装查询条件
const initForm = (form) => {
  form.deadline_at = {
    start: form.deadline_at[0] || "",
    end: form.deadline_at[1] || "",
  }
  let keys = ["sku"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
  })

  return form
}
</script>
<style lang="scss" scoped>
// :deep(.vxe-header--row:nth-child(2)) {
//   // .vxe-header--column {
//   //   background: #eff3fe !important;
//   // }
// }
:deep(.vxe-pager) {
  display: none;
}
</style>
